package com.quick.controller.monitor;

import com.quick.common.constants.CacheConstants;
import com.quick.common.core.domain.ApiResponse;
import com.quick.common.core.domain.Dict;
import com.quick.common.redis.RedisCache;
import com.quick.common.utils.DictUtils;
import com.quick.common.utils.StringUtils;
import com.quick.system.domain.SysCache;
import com.quick.system.domain.SysConfig;
import com.quick.system.domain.SysDictData;
import com.quick.system.service.SysConfigService;
import com.quick.system.service.SysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 缓存监控
 *
 * @Author: 吃素不吃肉
 * @Date: Tue Jul 25 14:14:44 CST 2023
 */
@RestController
@RequestMapping("/monitor/cache")
public class CacheController {
    @Autowired
    private SysDictDataService sysDictDataService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private RedisCache redisCache;

    private final static List<SysCache> CACHES = new ArrayList<>();

    static {
        CACHES.add(new SysCache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息"));
        CACHES.add(new SysCache(CacheConstants.SYS_CONFIG_KEY, "配置信息"));
        CACHES.add(new SysCache(CacheConstants.SYS_DICT_KEY, "数据字典"));
        CACHES.add(new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码"));
        CACHES.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交"));
        CACHES.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理"));
        CACHES.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数"));
    }

    /**
     * 初始化缓存数据
     */
    @PreAuthorize("@ps.hasPermission('monitor:cache:list')")
    @GetMapping()
    public ApiResponse getInfo() throws Exception {
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::info);
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        Object dbSize = redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::dbSize);
        Map<String, Object> result = new HashMap<>(3);
        result.put("info", info);
        result.put("dbSize", dbSize);
        List<Map<String, String>> pieList = new ArrayList<>();
        if (Objects.nonNull(commandStats)) {
            commandStats.stringPropertyNames().forEach(key -> {
                Map<String, String> data = new HashMap<>(2);
                String property = commandStats.getProperty(key);
                data.put("name", StringUtils.removeStart(key, "cmdstat_"));
                data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
                pieList.add(data);
            });
        }
        result.put("commandStats", pieList);
        return ApiResponse.success(result);
    }

    @PreAuthorize("@ps.hasPermission('monitor:cache:list')")
    @GetMapping("/getNames")
    public ApiResponse cache() {
        return ApiResponse.success(CACHES);
    }

    @PreAuthorize("@ps.hasPermission('monitor:cache:list')")
    @GetMapping("/getKeys/{cacheName}")
    public ApiResponse getCacheKeys(@PathVariable String cacheName) {
        Set<String> cacheKeys = redisTemplate.keys(cacheName + "*");
        return ApiResponse.success(cacheKeys);
    }

    @PreAuthorize("@ps.hasPermission('monitor:cache:list')")
    @GetMapping("/getValue/{cacheName}/{cacheKey}")
    public ApiResponse getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey) {
        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        SysCache sysCache = new SysCache(cacheName, cacheKey, cacheValue);
        return ApiResponse.success(sysCache);
    }

    @PreAuthorize("@ps.hasPermission('monitor:cache:list')")
    @DeleteMapping("/clearCacheName/{cacheName}")
    public ApiResponse clearCacheName(@PathVariable String cacheName) {
        Collection<String> cacheKeys = redisTemplate.keys(cacheName + "*");
        if (!CollectionUtils.isEmpty(cacheKeys)) {
            redisTemplate.delete(cacheKeys);
        }
        return ApiResponse.success();
    }

    @PreAuthorize("@ps.hasPermission('monitor:cache:list')")
    @DeleteMapping("/clearCacheKey/{cacheKey}")
    public ApiResponse clearCacheKey(@PathVariable String cacheKey) {
        redisTemplate.delete(cacheKey);
        return ApiResponse.success();
    }

    @PreAuthorize("@ps.hasPermission('monitor:cache:list')")
    @DeleteMapping("/clearCacheAll")
    public ApiResponse clearCacheAll() {
        Collection<String> cacheKeys = redisTemplate.keys("*");
        if (!CollectionUtils.isEmpty(cacheKeys)) {
            redisTemplate.delete(cacheKeys);
        }
        return ApiResponse.success();
    }
}
